package com.note.backend.service.impl.file;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.note.backend.mapper.NoteMapper;
import com.note.backend.pojo.Note;
import com.note.backend.pojo.Repository;
import com.note.backend.service.file.NoteService;
import com.note.backend.service.file.RepositoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@RequiredArgsConstructor
@Service
public class NoteServiceImpl implements NoteService {

    private final NoteMapper noteMapper;

    private final RepositoryService repositoryService;

    @Override
    public Note createNote(String title, String content, Integer repositoryId, Integer userId) {
        // 如果repositoryId不为空，验证仓库是否存在
        if (repositoryId != null) {
            Repository repository = repositoryService.getRepositoryById(repositoryId);
            if (repository == null) {
                throw new RuntimeException("仓库不存在");
            }
            // 验证仓库是否属于当前用户
            if (!repository.getUserId().equals(userId)) {
                throw new RuntimeException("无权访问该仓库");
            }
        }

        Note note = new Note();
        note.setTitle(title);
        note.setContent(content);
        note.setRepositoryId(repositoryId);
        note.setUserId(userId);
        note.setCreateTime(LocalDateTime.now());
        note.setUpdateTime(LocalDateTime.now());

        int result = noteMapper.insert(note);
        if (result <= 0) {
            throw new RuntimeException("创建随记失败");
        }
        return note;
    }

    @Override
    public Note saveNote(String title, String content, Integer noteId, Integer userId) {
        if (noteId != null) {
            // 更新已存在的笔记
            Note existingNote = noteMapper.selectById(noteId);
            if (existingNote == null) {
                throw new RuntimeException("随记不存在");
            }
            if (!existingNote.getUserId().equals(userId)) {
                throw new RuntimeException("无权修改该随记");
            }

            existingNote.setTitle(title);
            existingNote.setContent(content);
            existingNote.setUpdateTime(LocalDateTime.now());

            int result = noteMapper.updateById(existingNote);
            if (result <= 0) {
                throw new RuntimeException("更新随记失败");
            }
            return existingNote;
        } else {
            // 创建新笔记
            Note note = new Note();
            note.setTitle(title);
            note.setContent(content);
            note.setId(noteId);
            note.setUserId(userId);
            note.setCreateTime(LocalDateTime.now());
            note.setUpdateTime(LocalDateTime.now());

            int result = noteMapper.insert(note);
            if (result <= 0) {
                throw new RuntimeException("创建随记失败");
            }
            return note;
        }
    }

    @Override
    public Note createDocument(String title, Integer noteId, Integer userId) {
        Note note = new Note();
        note.setTitle(title);
        note.setUserId(userId);
        note.setId(noteId);
        note.setCreateTime(LocalDateTime.now());
        note.setUpdateTime(LocalDateTime.now());
        int result = noteMapper.insert(note);
        if (result <= 0) {
            throw new RuntimeException("创建随记失败");
        }
        return note;
    }


    @Override
    public List<Note> getNotesByRepositoryId(Integer repositoryId) {
        QueryWrapper<Note> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("repository_id", repositoryId);
        queryWrapper.orderByDesc("update_time");
        return noteMapper.selectList(queryWrapper);
    }

    @Override
    public List<Note> getNotesByUserId(Integer userId) {
        QueryWrapper<Note> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("update_time");
        return noteMapper.selectList(queryWrapper);
    }

    @Override
    public Note getNoteById(Integer id) {
        Note note = noteMapper.selectById(id);
        if (note == null) {
            throw new RuntimeException("随记不存在");
        }
        return note;
    }

    @Override
    public void deleteNote(Integer id, Integer userId) {
        QueryWrapper<Note> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("user_id", userId);

        int result = noteMapper.delete(queryWrapper);
        if (result <= 0) {
            throw new RuntimeException("删除随记失败");
        }
    }

    @Override
    public void addNoteToRepository(Integer noteId, Integer repositoryId, Integer userId) {
        UpdateWrapper<Note> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", noteId).eq("user_id", userId)
                .set("repository_id", repositoryId)
                .set("update_time", LocalDateTime.now());

        int result = noteMapper.update(null, updateWrapper);
        if (result <= 0) {
            throw new RuntimeException("添加随记到知识库失败");
        }
    }

    @Override
    public void removeNoteFromRepository(Integer noteId, Integer userId) {
        UpdateWrapper<Note> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", noteId).eq("user_id", userId)
                .set("repository_id", null)
                .set("update_time", LocalDateTime.now());

        int result = noteMapper.update(null, updateWrapper);
        if (result <= 0) {
            throw new RuntimeException("从知识库移除随记失败");
        }
    }
}